JwtStrategy.validate   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 7
dl 0
loc 8
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1 7
import { Injectable, UnauthorizedException } from '@nestjs/common';
2 7
import { PassportStrategy } from '@nestjs/passport';
3 7
import { ExtractJwt, Strategy } from 'passport-jwt';
4 7
import { ConfigService } from '@nestjs/config';
5
import { JwtPayload } from '../types/jwt-payload.interface';
6 7
import { AuthService } from '../auth.service';
7
8
@Injectable()
9 7
export class JwtStrategy extends PassportStrategy(Strategy) {
10
  constructor(
11 5
    private configService: ConfigService,
12 5
    private authService: AuthService,
13
  ) {
14
    // const secret = process.env.JWT_SECRET || 'your-secret-key';
15
    // console.log('JwtStrategy initialized with secret:', secret);
16 5
    super({
17
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
18
      ignoreExpiration: false,
19
      secretOrKey: configService.get<string>('JWT_SECRET'),
20
    });
21
  }
22
23
  async validate(payload: JwtPayload) {
24
    // this is not stateless, as we query the db. This can be refactored to be stateless, the token contains all user data.
25 30
    const user = await this.authService.validateUserById(payload.sub);
26 30
    if (!user) {
27 2
      throw new UnauthorizedException();
28
    }
29 28
    return user;
30
  }
31
}
32